package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingMapper orderSettingMapper;

    @Override
    public void addOrderSetting(List<OrderSetting> list) {
        //判空
        if (list != null && list.size() > 0){
            //遍历该集合
            for (OrderSetting orderSetting : list) {
                //先判断该日期是否存在
                OrderSetting order = orderSettingMapper.findByData(orderSetting.getOrderDate());
                //如果不为空,更新日期,为空,新建
                if (order == null){
                    orderSettingMapper.addOrderSetting(orderSetting);
                }else {
                    orderSettingMapper.updateNumber(orderSetting);
                }
            }
        }


    }

    @Override
    public List<Map> findOrderSetting(String date) {
        //在数据库中直接查询日期,是单个的日期,这里需要查询的是当月的数据,不论怎么查询都是月初到月末
        String begin = date + "- 1";
        String end = date + "-31";
        //数据库查询需要两个参数,封装成map集合进行传参,也可以用param进行多参数查询
        Map<String,String> map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        //查询得到的结果是ordersetting的类的集合
        List<OrderSetting> listOrderSetting = orderSettingMapper.findOrderSetting(map);
        //遍历该集合,并将其封装到 List<Map>
        List<Map> list = new ArrayList<>();
        //这里要先对listOrderSetting进行判空,否则容易报空指针
        if (listOrderSetting != null && listOrderSetting.size() > 0) {
            for (OrderSetting orderSetting : listOrderSetting) {
                //{ date: 1, number: 120, reservations: 1 }
                Map oMap = new HashMap();
                oMap.put("date", orderSetting.getOrderDate().getDay());
                oMap.put("number", orderSetting.getNumber());
                oMap.put("reservations", orderSetting.getReservations());
                list.add(oMap);
            }
            return list;
        }
        return null;
    }

    @Override
    public void updateNumber(OrderSetting orderSetting) {
        //先根据日期进行查询当前日期是否进行了预约设置,如果没设置执行添加操作,如果设置,执行更新操作
        OrderSetting order = orderSettingMapper.findByData(orderSetting.getOrderDate());
        if (order == null){
            orderSettingMapper.addOrderSetting(orderSetting);
        }else{
            orderSettingMapper.updateNumber(orderSetting);
        }
    }
}
